<?php
/**
 * 聊天
 * User: Tsang
 * Date: 2017/12/22 11:17
 *
 */

namespace app\api\logic;


use app\api\BaseModel;
use think\Cache;
use think\Loader;

class Chat extends BaseModel
{


    /**
     * 创建账号
     */
    public function create_user($nick,$userid,$pwd,$icon_url,$type,$typeid){
        $m_chat = db('chat');
        $chat = $m_chat->where(['nickname' => $nick])->find();
        if($chat) return array('message' => '重复的昵称');
        Loader::import('Openim.TopSdk', EXTEND_PATH, '.php');
        $c = new \TopClient();
        $c->appkey = config('openim.appkey');
        $c->secretKey = config('openim.secretKey');
        $req = new \OpenimUsersAddRequest;
        $userinfos = new \Userinfos;
        $userinfos->nick = $nick;
        $userinfos->userid = $userid;
        $userinfos->password = $pwd;
        $userinfos->icon_url=$icon_url;
        $req->setUserinfos(json_encode($userinfos));
        $resp = object_to_array($c->execute($req));
        if(isset($resp['uid_succ']['string']) && $userid == $resp['uid_succ']['string']){
            if(!$m_chat->insert(['userid' => $userid,'create_time' => TIMESTAMP,'typeid' => $typeid,'type' => $type,'nickname' => $nick,'pwd' => $pwd])){
                return array('message' => '添加失败');
            }
            return array();
        }else{
            return array('message' => '系统错误');
        }

    }


    /*
    *修改百川账号接口
    */
    public function set_user($user_info,$userid){
        if(empty($user_info['nickname']) && empty($user_info['headimage'])) return array('message'=>'参数为空');

        Loader::import('Openim.TopSdk', EXTEND_PATH, '.php');
        $c = new \TopClient();
        $c->appkey = config('openim.appkey');
        $c->secretKey = config('openim.secretKey');
        $req = new \OpenimUsersUpdateRequest;

        $userinfos = new \Userinfos;

        if(!empty($user_info['nickname'])){
            $m_chat = db('chat');
            $chat = $m_chat->where(['nickname' => $user_info['nickname']])->find();
            if($chat) return array('message' => '重复的昵称');
            $userinfos->nick = $user_info['nickname'];
        }

        if(!empty($user_info['headimage'])){
            $userinfos->icon_url = $user_info['headimage'];
        }

        $userinfos->userid = $userid;

        $req->setUserinfos(json_encode($userinfos));

        $resp = object_to_array($c->execute($req));

        return $resp;
    }


    /**
     * 获取聊天列表
     */
    public function chatList($id){
        $chat = db('chat')->where(['id' => $id])->find();
        if(!$chat) return array('message' => '找不到聊天账号');
        if(Cache::has('chat'.$chat['id'])){
            $list = json_decode(Cache::get('chat'.$chat['id']),true);
            // foreach ($list as $key => $value) {
            //     $uid = $value['id'];
            //     $typeid = db('chat')->where(['id' => $uid])->field('typeid')->find();
            //     $nickname = db('member')->where(['id' => $typeid['typeid']])->field('nickname')->find();
            //     $list[$key]['nickname'] = $nickname['nickname'];
            // }

            $uids = array();
            foreach ($list as $key => $value) {
                $uids[$key] = $value['id'];    
            }
            $m_id = db('chat')->where('id','in',$uids)->order(['id'=>'desc'])->field('typeid')->select();
            $typeid = array();
            foreach  ($m_id as $key => $value) {
                $typeid[$key] = $value['typeid'];
            }
            $nickname = db('member')->where('id','in',$typeid)->order(['id'=>'desc'])->field('nickname')->select();
            $nk = array();
            foreach ($nickname as $key => $value) {
                $nk[$key] = $value['nickname'];
            }
            foreach ($list as $key => $value) {
                $list[$key]['nickname'] = $nk[$key];
            }

            $refresh = Cache::has('chat_refresh'.$chat['id']) ? Cache::get('chat_refresh'.$chat['id']) : 0;
            return array('list' => $list,'refresh' => $refresh);
        }else{
            return array();
        }
    }

    /**
     * 设置聊天缓存
     */
    public function setChatCache($uid,$to_uid,$goods_id){
        if(empty($to_uid)) return array('message' => '对话ID不能为空');
        $m_chat = db('chat');
        $touser = $m_chat->where(['userid' => $to_uid])->find();
        if (!$touser) return array('message' => '找不到对方账号');
        $user = $m_chat->where(['typeid' => $uid])->find();
        if(!$user) return array('message' => '找不到聊天账号');
        if(Cache::has('chat'.$touser['id'])){
            $record = json_decode(Cache::get('chat'.$touser['id']),true);
            $key = array_search($user['id'],array_column($record,'id'));
            if($key === false){
                $data = array(
                    'id' => $user['id'],
                    'num' => 1,
                    'nickname' => $user['nickname']
                );
                if($goods_id > 0){
                    $data['goods_id'] = $goods_id;
                }
                array_unshift($record,$data);
            }else{
                $record[$key]['num'] += 1;
                if($goods_id > 0){
                    $record[$key]['goods_id'] = $goods_id;
                }
                array_unshift($record,$record[$key]);
                unset($record[$key+1]);
                $record = array_merge($record);
            }
            Cache::set('chat'.$touser['id'],json_encode($record));
        }else{
            $data = array(
                'id' => $user['id'],
                'num' => 1,
                'nickname' => $user['nickname']
            );
            if($goods_id > 0){
                $data['goods_id'] = $goods_id;
            }
            $record[] = $data;
            Cache::set('chat'.$touser['id'],json_encode($record));
        }
        if(Cache::has('chat'.$user['id'])){
            $record = json_decode(Cache::get('chat'.$user['id']),true);
            $key = array_search($touser['id'],array_column($record,'id'));
            if($key !== false){
                $record[$key]['num'] = 0;
                Cache::set('chat'.$user['id'],json_encode($record));
            }
        }
        return array();
    }


    /**
     * 阅读信息
     */
    public function readChat($uid,$touid){
        $m_chat = db('chat');
        $chat = $m_chat->where(['id' => $uid])->find();
        if(!$chat) return array('message' => '找不到聊天账号');
        $user = $m_chat->where(['id' => $touid])->find();
        if(!$user) return array('message' => '找不到对方聊天账号');
        if(Cache::has('chat'.$chat['id'])){
            $data = json_decode(Cache::get('chat'.$chat['id']),true);
            if(!empty($data)){
                $key = array_search($user['id'],array_column($data,'id'));
                if($key !== false){
                    $data[$key]['num'] = 0;
                    Cache::set('chat'.$chat['id'],json_encode(array_merge($data)));
                }
            }
        }
        return array();
    }

}